#if UNITY_EDITOR || UNITY_OPENHARMONY
using UnityEngine;

namespace NativeCameraNamespace
{
    public class NCCameraCallbackOH : MonoBehaviour
    {
        private static NCCameraCallbackOH instance;
        private System.Action mainThreadAction = null;
        
        private NativeCamera.CameraCallback callback;
        
        public static void Initialize( NativeCamera.CameraCallback callback )
        {
            if( instance == null )
            {
                instance = new GameObject( "NCCameraCallbackOH" ).AddComponent<NCCameraCallbackOH>();
                DontDestroyOnLoad( instance.gameObject );
            }

            instance.callback = callback;
            instance.mainThreadAction = null;
        }
        
		
        private void Update()
        {
            if( instance.mainThreadAction != null )
            {
                try
                {
                    System.Action temp = instance.mainThreadAction;
                    instance.mainThreadAction = null;
                    temp();
                }
                finally
                {
                    Destroy( instance.gameObject );
                }
            }
        }

        private void CallOnMainThread( System.Action function )
        {
            instance.mainThreadAction = function;
        }
        
        
        [UnityEngine.Scripting.Preserve]
        public void OnMediaReceived( string path )
        {
            instance.CallOnMainThread( () => instance.callback( !string.IsNullOrEmpty( path ) ? path : null ) );
        }
        
    }
}
#endif